package com.medisign.sign.log.util;

import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;

/**
 * @author ljt
 * @version 1.0
 * @description:
 * @date 2021/7/14 14:16
 */
@RequiredArgsConstructor
@Component
public class HttpClientUtil {

    protected static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    private final RestTemplate restTemplate;

    public String post(String url, String param) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity reqEntity =new HttpEntity(param, headers);
        String respResult = restTemplate.postForObject(url, reqEntity, String.class);
        return respResult;
    }

    public String get(String url) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));

        HttpEntity entity = new HttpEntity(null, headers);
        ResponseEntity<String> resEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        if (HttpStatus.OK.value() == resEntity.getStatusCode().value()) {
            return resEntity.getBody();
        }else {
            throw new RuntimeException("请求失败!");
        }
    }

}
